﻿using System;
using System.IO;
using System.Web;

using Yawf.Core.Exceptions;
using Yawf.Core.Logs;
using Yawf.Core.Utils;
using Yawf.Security;
using Yawf.Security.Entities;
using Yawf.Web.Utils;
using Yawf.Web.Managers;
using Yawf.Web.Managers.Entities;

namespace Yawf.Web.Managers {
	public class SimpleErrorManager : IErrorManager{

		// Properties
		public IModelViewerManager ViewManager { get; set; }
		public String ErrorResource { get; set; }
		public String AccessDeniedResource { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="requestWrapper">RequestWrapper object to use</param>
		/// <param name="responseWrapper">ResponseWrapper object to use</param>
		/// <param name="resourcePath">path to resource where error happend</param>
		/// <param name="user">currently logged on user</param>
		/// <param name="e">VCGException that triggered this method</param>
		public void HandleError(RequestWrapper requestWrapper, ResponseWrapper responseWrapper, String resourcePath, IUser user, YawfException e) {
			View view;
			String errResource = null;

			if (e is AuthorizationException) {
				errResource = AccessDeniedResource;
			}
			if (StringUtils.IsEmpty(errResource)) {
				errResource = ErrorResource;
			}
			if (StringUtils.IsEmpty(errResource)) {
				errResource = "~/error.xml";
			}

			try {
				// First log de exception for debug purpose
				Log.ExceptionMessage(GetType(), "Exception handle by SimpleErrorManager", e);
				// Add execption to ResponseWrapper
				responseWrapper.Add(e,"errorException");

				if (ResourceUtils.DoResourceExists(errResource)) {
					view = new View(errResource);
					responseWrapper.Response.ContentType = "text/html";
					ViewManager.ProcessView(requestWrapper,responseWrapper,view,user);
				} else {
					DisplayError(e,"Unhandled Error in Application",responseWrapper.Response);
				}
			} catch (Exception e1) {
				DisplayError(e1,"Error while forwarding to " + errResource,responseWrapper.Response);
			}
		}								// HandleError

		/**
		 * Debugging method to handle errors.  This version adds a stack
		 * trace for debugging.
		 *
		 * @param e the Exception object
		 * @param errorMsg any additional error message to be displayed
		 * @param res the HttpServletResponse object
		 */
		private void DisplayError(Exception e,String errorMsg,HttpResponse res){
			TextWriter oWriter;
		
			try{
				oWriter = res.Output;
				res.ContentType = "text/html";
				oWriter.WriteLine("Error: " + errorMsg + ", Caused by " + e.ToString());
				oWriter.WriteLine("<pre>");
				oWriter.WriteLine(e.StackTrace);
				oWriter.WriteLine("</pre>");
			}catch(Exception ex){
				// Do nothing, we are handling error here so something is clearly wrong
				// just log exception
				Log.ExceptionMessage(this.GetType(),"Exception: " + ex,ex);
			}
		}					// DisplayError

	}											// Class
}
